﻿using JNPF.Saas.Logic.Tenant;
using JNPF.Saas.Logic.TenantLog;
using JNPF.Saas.Models.BaseTenant.Entities;
using JNPF.Saas.Models.Tenant.Dtos;
using JNPF.Saas.Models.Tenant.Entities;
using JNPF.Utils;
using JNPF.Utils.Controller;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;

namespace JNPF.Saas.Controller.BaseTenant
{
    /// <summary>
    /// 租户信息
    /// 版 本：V3.0.0
    /// 版 权：引迈信息技术有限公司（https://www.jnpfsoft.com）
    /// 作 者：JNPF开发平台组
    /// 日 期：2020.12.21 
    /// </summary>
    [Route("api/Saas/[controller]")]
    [AllowAnonymous]
    public class TenantController : BaseApiController
    {
        private TenantBll tenantBll = new TenantBll();
        private TenantLogBll tenantLogBll = new TenantLogBll();
        #region Get
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<ResponseResult> GetList(TenantListQuery input)
        {
            var pageInput = input.MapTo<PageInput>();
            pageInput.queryJson = new { input.endTime, input.startTime }.ToJson();
            var data = await tenantBll.GetList(pageInput);
            var output = new PageResult()
            {
                list = data.list.MapToList<TenantListOutput>(),
                pagination = data.pagination
            };
            return Success(output);
        }
        /// <summary>
        /// 信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<ResponseResult> GetInfo(string id)
        {
            var output = (await tenantBll.GetInfo(id)).MapTo<TenantInfoOutput>();
            return Success(output);
        }
        /// <summary>
        /// 获取租户数据库
        /// </summary>
        /// <param name="encode"></param>
        /// <returns></returns>
        [HttpGet("DbName/{encode}")]
        public async Task<ResponseResult> GetDbContent(string encode)
        {
            var data = await tenantBll.GetDbContent(encode);
            if (data == null)
            {
                return Error("租户不存在");
            }
            if (DateTime.Now > data.ExpiresTime)
            {
                return Error("租户已过期");
            }
            TenantLogEntity tenantLogEntity = new TenantLogEntity()
            {
                TenantId = data.Id,
                LoginAccount = encode,
                LoginIPAddress = data.IPAddress,
                LoginIPAddressName = data.IPAddressName,
                LoginSourceWebsite = data.SourceWebsite,
            };
            await tenantLogBll.Create(tenantLogEntity);
            var output = new TenantDbContentOutput();
            output.dbName = data.DbName;
            return Success(output);
        }
        #endregion

        #region Post
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ResponseResult> Create([FromBody] TenantCrInput input)
        {
            var count = (await tenantBll.GetList()).FindAll(x => x.EnCode.Equals(input.enCode)).Count;
            if (count > 0)
            {
                return Error("该账号已存在");
            }
            var entity = new TenantEntity()
            {
                FullName = input.fullName,
                EnCode = input.enCode,
                CompanyName = input.companyName,
                ExpiresTime = input.expiresTime == 0 ? DateTime.Now : CommonHelper.GetDateTime(input.expiresTime.ToString()),
                Description = input.description
            };
            var flag = await tenantBll.Create(entity);
            return flag > 0 ? Success("新增成功") : Error("新增失败");
        }
        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="input"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task<ResponseResult> Update([FromBody] TenantUpInput input, string id)
        {
            var entity = new TenantEntity()
            {
                FullName = input.fullName,
                EnCode = input.enCode,
                CompanyName = input.companyName,
                ExpiresTime = input.expiresTime == 0 ? DateTime.Now : CommonHelper.GetDateTime(input.expiresTime.ToString()),
                Description = input.description,
                Id = id
            };
            var flag = await tenantBll.Update(entity);
            return flag > 0 ? Success("修改成功") : Error("修改失败");
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="input"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<ResponseResult> Delete([FromBody] TenantDeleteQuery input, string id)
        {
            var entity = await tenantBll.GetInfo(id);
            if (entity == null)
            {
                return Error("数据不存在");
            }
            var flag = await tenantBll.Delete(entity, (int)input.isClear);
            return flag > 0 ? Success("删除成功") : Error("删除失败");
        }
        /// <summary>
        /// 创建租户数据库
        /// </summary>
        /// <param name="dbName">数据库名</param>
        /// <returns></returns>
        [HttpPost("DbName/{dbName}")]
        public async Task<ResponseResult> CreateDb(string dbName)
        {
            await tenantBll.CreateDB(dbName);
            return Success("创建成功");
        }
        #endregion
    }
}
